package com.example.score.utils;

import com.example.score.entity.Sportsman;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

public class SerializationUtils {
    public static void serializeSetToFile(Set<Sportsman> set) {
        // 生成时间戳
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = dateFormat.format(new Date());

        // 异步序列化到文件
        new Thread(() -> {
            try {
                String fileName = "sets_" + timestamp + ".ser";
                FileOutputStream fileOut = new FileOutputStream(fileName);
                ObjectOutputStream out = new ObjectOutputStream(fileOut);
                out.writeObject(set);
                out.close();
                fileOut.close();
                System.out.println("Sets serialized and saved to file: " + fileName);
            } catch (Exception e) {
                System.out.println("Error occurred during serialization: " + e.getMessage());
            }
        }).start();
    }

    public static Set<Sportsman> deserializeSetFromFile() {
        // 查找最新的序列化文件
        File folder = new File(".");
        File[] files = folder.listFiles((dir, name) -> name.startsWith("sets_") && name.endsWith(".ser"));
        File latestFile = null;
        long latestModifiedTime = 0;

        for (File file : files) {
            if (file.lastModified() > latestModifiedTime) {
                latestModifiedTime = file.lastModified();
                latestFile = file;
            }
        }

        if (latestFile == null) {
            System.out.println("No serialized file found.");
            return null;
        }

        // 反序列化文件并返回Set对象
        try {
            System.out.println("last serialize file " + latestFile.getName());
            FileInputStream fileIn = new FileInputStream(latestFile);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            Set<Sportsman> set = (Set<Sportsman>) in.readObject();
            in.close();
            fileIn.close();
            System.out.println("Set deserialized from file: " + latestFile.getName());
            return set;
        } catch (Exception e) {
            System.out.println("Error occurred during deserialization: " + e.getMessage());
            return null;
        }
    }
}
